package com.xhj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhj.client.MemberClient;
import com.xhj.entity.Comment;
import com.xhj.service.CommentService;
import com.xhj.util.JwtUtil;
import com.xhj.util.ResultEntity;
import com.xhj.vo.MemberVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * 评论(EduComment)表控制层
 *
 * @author makejava
 * @since 2021-03-10 22:49:54
 */
@CrossOrigin
@RestController
@RequestMapping("/EduAdmin/comment/")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private MemberClient memberClient;

    @ApiOperation(value = "根据课程id查询评论分页列表")
    @RequestMapping("list/{page}/{limit}")
    public ResultEntity getPageList(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            @ApiParam(name = "courseId", value = "课程id", required = false) String courseId){
        Page<Comment> commentPage = new Page<>(page, limit);
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        commentService.page(commentPage, queryWrapper);

        return ResultEntity.successWithData()
                .data("items",commentPage.getRecords())
                .data("current",commentPage.getCurrent())
                .data("pages",commentPage.getPages())
                .data("size",commentPage.getSize())
                .data("total",commentPage.getTotal())
                .data("hasNext",commentPage.hasNext())
                .data("hasPrevious",commentPage.hasPrevious());
    }

    @ApiOperation(value = "添加评论")
    @RequestMapping("saveComment")
    public ResultEntity saveComment(
            @ApiParam(name = "comment",value = "评论对象",required = true)
            @RequestBody Comment comment,
            HttpServletRequest request){
        // 根据token获得用户id
        String memberId = JwtUtil.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) return ResultEntity.failedWithMessage("请登录！").setCode(28004);
        // 根据用户id获取用户相关信息
        MemberVo member = memberClient.getMemberInfoById(memberId);
        comment.setMemberId(memberId);
        comment.setNickname(member.getNickname());
        comment.setAvatar(member.getAvatar());
        commentService.save(comment);

        return ResultEntity.successWithoutData();
    }
}